package gpl.pierrick.brihaye.aramorph;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

/**
 * A compatibility table that reads from database
 * @author Ahmed Saad
 */
public class JDBCCompatibilityTable implements CompatibilityTable {
	/**A logger to write log messages*/
	private static Logger logger = Logger.getLogger(JDBCCompatibilityTable.class.getName());

	/**A readonly connection to database*/
	protected DBManager readonlyConnection = DBManager.readonlyConnection;
	
	/**Name of this table in the database*/
	protected final String tableName;
	
	/**
	 * Constructs a new compatibility table with the given name
	 * @param tableName name of the table in the database
	 */
	public JDBCCompatibilityTable(String tableName) {
		this.tableName = tableName;
	}

	public boolean contains(String first, String second) {
		return readonlyConnection.containsEntry(tableName,first+' '+second,false);
	}
	
	/**
	 * Creates the database (fills in tables) from the XML compatibility tables.
	 * @param xmlFile an input stream to the XML file to be loaded.
	 */
	public void createFromXML(InputStream is) {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		factory.setValidating(false);
		try {
			SAXParser sax = factory.newSAXParser();
			XMLCompatibilityReader dl = new XMLCompatibilityReader(tableName);
			sax.parse(is,dl);
//			dl.writeStats();
		} catch (ParserConfigurationException pce) {
			logger.warning("Could not create that parser.");
			logger.warning(pce.getMessage());
		} catch (SAXException se) {
			logger.warning("Problem with the SAX parser");
			logger.warning(se.getMessage());
		} catch (IOException ioe) {
			logger.warning("Error reading file.");
			logger.warning(ioe.getMessage());
		}
	}

}

class XMLCompatibilityReader extends XMLCompatibilityLoader{
	/**Name of database table to be filled*/
	private final String tableName;

	/**A connection to database that can insert values*/
	private DBManager dbUpdateConnection = DBManager.getUpdateConnection();
	
	public XMLCompatibilityReader(String tableName) {
		super(null);
		this.tableName = tableName;
	}

	@Override
	public void startDocument() throws SAXException {
		dbUpdateConnection.clearTable(tableName);
	}

	@Override
	protected void entryLoaded(String first, String second) {
		dbUpdateConnection.addCompatibilityEntry(tableName,first+' '+second);
	}
}